// 创建一个名为upload.ts的模块

import { ref, reactive } from 'vue';
// import { chooseFile, uploadFile, getFileInfo } from '@dcloudio/uni-app';

interface UploadResult {
	url: string;
	filePath: string;
}

interface UploadOptions {
	count:number;
	maxSize?: number; // 最大允许上传文件大小（单位字节）
	fileType?: string[]; // 允许上传的文件类型数组，例如：['image', 'video']
	
}

export default function useUploader(options: UploadOptions = {
	count: 1
}) {
	const fileState = reactive<UploadResult | any>(null);
	const error = ref<string>('');
	let file = reactive<object | any>(null);
	let maxSizeLimit = options.maxSize || 0;
	async function selectFile() {
		return new Promise((resolve, reject) => {
			try {
				// const allowedTypes = options.fileType || ['*'];

				if (typeof maxSizeLimit !== 'number') {
					// 如果未定义或不是数字类型，则设置一个默认值（例如10MB）
					maxSizeLimit = 1024 * 1024 * 10; // 默认最大允许上传文件大小为10MB
				}
				uni.chooseImage({
					count: options.count,
					type: 'all',
					sizeType: ['compressed'], // 可选原图或压缩图，默认为所有类型
					sourceType: ['album', 'camera'], // 图片来源
					success: (ret) => {
						file = ret;
						file ? resolve(file) : reject('上传失败');
					},
					fail: (error) => {
						reject(error);
					},
				});
			} catch (err: any) {
				error.value = err.message;
				reject(err);
			}
		});
	}

	async function upload(tempFilePaths:any, uploadUrl: string) {
		const useStores = UseStore();
		if (tempFilePaths.length==0) {
			uni.showToast({
				title: '未选择任何图片',
				icon: 'error',
			});
			return;
		}
		uni.showLoading({
			title: '上传中',
		});
		return new Promise((resolve,reject)=>{
			try {
				for (let i = 0; i < tempFilePaths.length; i++){
					
					uni.uploadFile({
						url: uploadUrl,
						filePath: tempFilePaths[i],
						name: 'file',
						header: {
							token: useStores.getUserToken,
						},
						success: (response) => {
							
							if (response.statusCode === 200) {
								const update = JSON.parse(response.data);
								uni.hideLoading();
								resolve(update)
							} else {
								uni.hideLoading();
								reject(response)
							}
						},
						fail: (err) => {
							console.log('err',err)
							uni.hideLoading();
							reject(err)
							
							
						},
					});
				}
				
			} catch (err: any) {
				
				uni.hideLoading();
				error.value = err.message;
				reject(err)
			}
		})
		
	}

	return {
		fileState,
		error,
		selectFile,
		upload,
	};
}
